package server.main.config.springsecurity.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import server.main.mapper.AccountMapper;
import server.main.pojo.Account;
import server.main.service.AccountService;
import server.main.service.AfterService;


import java.util.List;

/**
 * @auther MingHsZzz
 * @create 2022-08-29-16:04
 */

@Service("UserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    AccountService accountService;
//    AccountService accountService = new AccountServiceImpl();
    @Autowired
    AccountMapper accountMapper;

    @Autowired
    AfterService afterService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Account user = accountService.getOne(
                new LambdaQueryWrapper<Account>().eq(Account::getUsername, username)
        );

        if (user == null) {
            throw new UsernameNotFoundException("账户不存在！");
        }
        //获取用户权限信息,仅获取到角色名称并未获取进获取名称未获取到具体路由
        user.setRoles(accountMapper.getUserRolesByJobnum(username));


//        System.out.println("roles" + user.getRoles());
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
//        return new User(user.getUsername(),user.getPassword(),list);
//        System.out.println("username"+username);
//        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),list);
//        System.out.println(user);
        return user;
    }
}
